import router from '@/router'
import axios from 'axios'

const baseUrl = 'http://127.0.0.1:6066/admin'

const service = axios.create()

// 请求拦截
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('milk_mamage_token')
    const baseHeaders = {
      Authorization: `${token}`
    }
    if (token) {
      config.headers = {
        ...config.headers,
        ...baseHeaders
      }
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截
service.interceptors.response.use(
  (res) => {
    const { code, msg } = res.data
    if (code === 401) {
      setTimeout(() => {
        router.push({ name: 'login' })
      }, 3000)
      // localStorage.setItem('milk_mamage_token', '')
      res.data.msg = msg + '登录状态过期，请重新登录'
    }
    return res
  },
  error => Promise.reject(error)
)

type RequestOptions = {
  restful?: boolean; // 是否开启 restful 状态码解析
  statusKey?: string; // 状态码 key
  successCode?: number | string; // 请求成功下的 code 值
};

export default async function ajax <T> (_url: string, _data: object = {}, type = 'get', opts?: RequestOptions): Promise<T> {
  const url = new URL(baseUrl + _url)
  let resp

  if (type === 'get') {
    Object.entries(_data).forEach(([k, v]) => {
      url.searchParams.append(k, v)
    })
    resp = await service.get(url.toString())
  } else {
    resp = await service.post(url.toString(), _data)
  }

  const ticketData = resp.data
  const ret = new Promise<T>((resolve, reject) => {
    const {
      restful = true,
      statusKey = 'code',
      successCode = 200
    } = opts ?? {}
    if (restful && ticketData[statusKey] !== successCode) {
      reject(new Error(ticketData.msg))
    }
    resolve(restful ? ticketData.data : ticketData)
  })
  return ret
}
